package com.yulang.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yulang.entity.SysPermission;
import com.yulang.entity.SysRole;
import com.yulang.mapper.SysPermissionMapper;
import com.yulang.security.result.Result;
import com.yulang.service.SysRoleService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/role")
public class SystemRoleController {


    public final static String HTML_PREFIX = "system/role";


    @Autowired
    private SysRoleService service;

    @Autowired
    private SysPermissionMapper sysPermissionMapper;

    @PreAuthorize("hasAnyAuthority('sys:role')")
    @GetMapping(value = {"/",""})
    public String user() {
        return HTML_PREFIX+"/role-list";
    }


    @PreAuthorize("hasAnyAuthority('sys:role:list')")
    @ResponseBody
    @PostMapping("/page")
    public Result page(Page<SysRole> page, SysRole sysRole) {
        QueryWrapper<SysRole> query = new QueryWrapper<>();
        query.lambda().like(StringUtils.isNotEmpty(sysRole.getName()),SysRole::getName,sysRole.getName());
        IPage<SysRole> page1 = service.page(page, query);
        return Result.ok(page1);
    }


    @PreAuthorize("hasAnyAuthority('sys:role:add','sys:role:edit')")
    @GetMapping(value = {"/form","/form/{id}"})
    public String form(@PathVariable(required = false) String id, Model model) {
        SysRole sysRole = new SysRole();
        if(StringUtils.isNotEmpty(id)) {
            sysRole = service.getById(id);
            List<SysPermission> sysPermissions = sysPermissionMapper.selectPermissionByRoleId(id);
            sysRole.setPerList(sysPermissions);
        }
        model.addAttribute("role",sysRole);
        return HTML_PREFIX+"/role-form";
    }


    @PostMapping
    @PreAuthorize("hasAnyAuthority('sys:role:add','sys:role:edit')")
    public String add(SysRole sysRole) {
        service.saveOrUpdateRole(sysRole);
        return "redirect:/role";
    }


    @ResponseBody
    @PreAuthorize("hasAnyAuthority('sys:role:delete')")
    @PostMapping("/{id}")
    public Result delete(@PathVariable String id) {
        service.removeById(id);
        return Result.ok();
    }




}
